import { Direction, NodeData, Location, Size } from './models'

export class Node {
    id = null
    index = null
    topic = null
    data = null
    isroot = false
    parent = null
    direction = Direction.Left
    expanded = false
    children: Node[] = []
    _data: NodeData

    constructor (sId: string | number, iIndex: number, sTopic: string, oData: any, bIsRoot: boolean, oParent?: Node, eDirection?: Direction, bExpanded?: boolean){
        if(!sId){console.error('invalid nodeid');return;}
        if(typeof iIndex != 'number'){console.error('invalid node index');return;}
        if(typeof bExpanded === 'undefined'){bExpanded = true;}
        this.id = sId;
        this.index = iIndex;
        this.topic = sTopic;
        this.data = oData || {};
        this.isroot = bIsRoot;
        this.parent = oParent;
        this.direction = eDirection;
        this.expanded = !!bExpanded;
        this.children = [];
        this._data = {};
    };

    /**
     * 比较两个 Node 对象的顺序，依据 index 属性
     * @param node1 
     * @param node2 
     */
    static compare (node1: Node, node2: Node): number {
        var r = 0;
        var i1 = node1.index;
        var i2 = node2.index;
        if(i1>=0 && i2>=0){
            r = i1-i2;
        }else if(i1==-1 && i2==-1){
            r = 0;
        }else if(i1==-1){
            r = 1;
        }else if(i2==-1){
            r = -1;
        }else{
            r = 0;
        }
        return r;
    }

    /**
     * 判断 node 是否是 pnode 的后继节点（包括节点本身）
     * @param pnode 
     * @param node 
     */
    static inherited (pnode: Node, node: Node): boolean {
        if(!!pnode && !!node){
            if(pnode.id === node.id){
                return true;
            }
            if(pnode.isroot){
                return true;
            }
            var pid = pnode.id;
            var p = node;
            while(!p.isroot){
                p = p.parent;
                if(p.id === pid){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取 Node 对象的绝对位置
     */
    getLocation (): Location {
        let vd = this._data.view
        return {
            x: vd.abs_x,
            y: vd.abs_y
        }
    }

    getSize (): Size {
        let vd = this._data.view
        return {
            w: vd.width,
            h: vd.height
        }
    }

}